
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_Hans">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>内容类型框架 &#8212; Django 3.2.6.dev 文档</title>
    <link rel="stylesheet" href="../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../_static/doctools.js"></script>
    <script type="text/javascript" src="../../_static/language_data.js"></script>
    <link rel="index" title="索引" href="../../genindex.html" />
    <link rel="search" title="搜索" href="../../search.html" />
    <link rel="next" title="简单页面应用" href="flatpages.html" />
    <link rel="prev" title="django.contrib.auth" href="auth.html" />



 
<script src="../../templatebuiltins.js"></script>
<script>
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);</script>

  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../../index.html">Django 3.2.6.dev 文档</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../../index.html">Home</a>  |
        <a title="Table of contents" href="../../contents.html">Table of contents</a>  |
        <a title="Global index" href="../../genindex.html">Index</a>  |
        <a title="Module index" href="../../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="auth.html" title="&lt;code class=&#34;docutils literal notranslate&#34;&gt;&lt;span class=&#34;pre&#34;&gt;django.contrib.auth&lt;/span&gt;&lt;/code&gt;">previous</a>
     |
    <a href="../index.html" title="API 参考" accesskey="U">up</a>
   |
    <a href="flatpages.html" title="简单页面应用">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="ref-contrib-contenttypes">
            
  <div class="section" id="s-module-django.contrib.contenttypes">
<span id="s-the-contenttypes-framework"></span><span id="module-django.contrib.contenttypes"></span><span id="the-contenttypes-framework"></span><h1>内容类型框架<a class="headerlink" href="#module-django.contrib.contenttypes" title="永久链接至标题">¶</a></h1>
<p>Django 包含了一个 <a class="reference internal" href="#module-django.contrib.contenttypes" title="django.contrib.contenttypes: Provides generic interface to installed models."><code class="xref py py-mod docutils literal notranslate"><span class="pre">contenttypes</span></code></a> 应用程序，它可以跟踪所有安装在你的 Django 项目中的模型，为你的模型提供了一个高级的通用接口。</p>
<div class="section" id="s-overview">
<span id="overview"></span><h2>概况<a class="headerlink" href="#overview" title="永久链接至标题">¶</a></h2>
<p>内容类型应用的核心是 <a class="reference internal" href="#django.contrib.contenttypes.models.ContentType" title="django.contrib.contenttypes.models.ContentType"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentType</span></code></a> 模型，它位于 <code class="docutils literal notranslate"><span class="pre">django.contrib.contenttypes.models.ContentType</span></code>。<a class="reference internal" href="#django.contrib.contenttypes.models.ContentType" title="django.contrib.contenttypes.models.ContentType"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentType</span></code></a> 的实例代表和存储了你项目中安装的模型的信息，每当有新的模型安装时，就会自动创建 <a class="reference internal" href="#django.contrib.contenttypes.models.ContentType" title="django.contrib.contenttypes.models.ContentType"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentType</span></code></a> 的新实例。</p>
<p><a class="reference internal" href="#django.contrib.contenttypes.models.ContentType" title="django.contrib.contenttypes.models.ContentType"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentType</span></code></a> 的实例有方法用于返回它们所代表的模型类和查询这些模型中的对象。 <a class="reference internal" href="#django.contrib.contenttypes.models.ContentType" title="django.contrib.contenttypes.models.ContentType"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentType</span></code></a>  也有一个 <a class="reference internal" href="../../topics/db/managers.html#custom-managers"><span class="std std-ref">自定义管理器</span></a>，它增加了一些方法，用于处理 <a class="reference internal" href="#django.contrib.contenttypes.models.ContentType" title="django.contrib.contenttypes.models.ContentType"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentType</span></code></a>，以及为特定模型获取 <a class="reference internal" href="#django.contrib.contenttypes.models.ContentType" title="django.contrib.contenttypes.models.ContentType"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentType</span></code></a> 的实例。</p>
<p>你的模型和 <a class="reference internal" href="#django.contrib.contenttypes.models.ContentType" title="django.contrib.contenttypes.models.ContentType"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentType</span></code></a> 之间的关系也可以用来启用你的一个模型实例和你安装的任何模型实例之间的“通用 ”关系。</p>
</div>
<div class="section" id="s-installing-the-contenttypes-framework">
<span id="installing-the-contenttypes-framework"></span><h2>安装内容类型框架<a class="headerlink" href="#installing-the-contenttypes-framework" title="永久链接至标题">¶</a></h2>
<p>内容类型框架包含在由 <code class="docutils literal notranslate"><span class="pre">django-admin</span> <span class="pre">startproject</span></code> 创建的默认的 <a class="reference internal" href="../settings.html#std:setting-INSTALLED_APPS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">INSTALLED_APPS</span></code></a> 列表中，但是如果你已经删除了它，或者你手动设置了 <a class="reference internal" href="../settings.html#std:setting-INSTALLED_APPS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">INSTALLED_APPS</span></code></a> 列表，你可以通过在 <a class="reference internal" href="../settings.html#std:setting-INSTALLED_APPS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">INSTALLED_APPS</span></code></a> 配置中添加 <code class="docutils literal notranslate"><span class="pre">'django.contrib.contenttypes'</span></code> 来启用它。</p>
<p>一般来说，安装内容类型框架是个不错的主意；Django 的其他一些捆绑的应用程序都需要它：</p>
<ul class="simple">
<li>管理应用程序使用它来记录通过管理界面添加或更改的每个对象的历史。</li>
<li>Django 的 <a class="reference internal" href="../../topics/auth/index.html#module-django.contrib.auth" title="django.contrib.auth: Django's authentication framework."><code class="xref py py-mod docutils literal notranslate"><span class="pre">认证框架</span></code></a> 使用它将用户权限与特定模型绑定。</li>
</ul>
</div>
<div class="section" id="s-the-contenttype-model">
<span id="the-contenttype-model"></span><h2><code class="docutils literal notranslate"><span class="pre">ContentType</span></code> 模型<a class="headerlink" href="#the-contenttype-model" title="永久链接至标题">¶</a></h2>
<dl class="class">
<dt id="django.contrib.contenttypes.models.ContentType">
<em class="property">class </em><code class="descname">ContentType</code><a class="headerlink" href="#django.contrib.contenttypes.models.ContentType" title="永久链接至目标">¶</a></dt>
<dd><p><a class="reference internal" href="#django.contrib.contenttypes.models.ContentType" title="django.contrib.contenttypes.models.ContentType"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentType</span></code></a> 的每个实例都有两个字段，这两个字段合在一起，唯一地描述了一个安装的模型。</p>
<dl class="attribute">
<dt id="django.contrib.contenttypes.models.ContentType.app_label">
<code class="descname">app_label</code><a class="headerlink" href="#django.contrib.contenttypes.models.ContentType.app_label" title="永久链接至目标">¶</a></dt>
<dd><p>模型所属应用程序的名称。这是从模型的 <a class="reference internal" href="#django.contrib.contenttypes.models.ContentType.app_label" title="django.contrib.contenttypes.models.ContentType.app_label"><code class="xref py py-attr docutils literal notranslate"><span class="pre">app_label</span></code></a> 属性中提取的，并且只包括应用程序的 Python 导入路径的 <em>最后</em> 一部分；例如，<code class="docutils literal notranslate"><span class="pre">django.contrib.contenttypes</span></code> 就变成了 <code class="docutils literal notranslate"><span class="pre">contenttypes</span></code> 的 <a class="reference internal" href="#django.contrib.contenttypes.models.ContentType.app_label" title="django.contrib.contenttypes.models.ContentType.app_label"><code class="xref py py-attr docutils literal notranslate"><span class="pre">app_label</span></code></a>。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.contrib.contenttypes.models.ContentType.model">
<code class="descname">model</code><a class="headerlink" href="#django.contrib.contenttypes.models.ContentType.model" title="永久链接至目标">¶</a></dt>
<dd><p>模型类的名称。</p>
</dd></dl>

<p>此外，还有以下属性：</p>
<dl class="attribute">
<dt id="django.contrib.contenttypes.models.ContentType.name">
<code class="descname">name</code><a class="headerlink" href="#django.contrib.contenttypes.models.ContentType.name" title="永久链接至目标">¶</a></dt>
<dd><p>内容类型的可读名称。这是从模型的 <a class="reference internal" href="../models/fields.html#django.db.models.Field.verbose_name" title="django.db.models.Field.verbose_name"><code class="xref py py-attr docutils literal notranslate"><span class="pre">verbose_name</span></code></a> 属性中提取的。</p>
</dd></dl>

</dd></dl>

<p>让我们看一个例子来了解它是如何工作的。如果你已经安装了 <a class="reference internal" href="#module-django.contrib.contenttypes" title="django.contrib.contenttypes: Provides generic interface to installed models."><code class="xref py py-mod docutils literal notranslate"><span class="pre">contenttypes</span></code></a> 应用程序，然后添加 <a class="reference internal" href="sites.html#module-django.contrib.sites" title="django.contrib.sites: Lets you operate multiple websites from the same database and Django project"><code class="xref py py-mod docutils literal notranslate"><span class="pre">站点框架</span></code></a> 到你的 <a class="reference internal" href="../settings.html#std:setting-INSTALLED_APPS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">INSTALLED_APPS</span></code></a> 配置中，并运行 <code class="docutils literal notranslate"><span class="pre">manage.py</span> <span class="pre">migrate</span></code> 来安装它，模型 <a class="reference internal" href="sites.html#django.contrib.sites.models.Site" title="django.contrib.sites.models.Site"><code class="xref py py-class docutils literal notranslate"><span class="pre">django.contrib.sites.models.Site</span></code></a> 将被安装到你的数据库中。与它一起创建一个新的 <a class="reference internal" href="#django.contrib.contenttypes.models.ContentType" title="django.contrib.contenttypes.models.ContentType"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentType</span></code></a> 实例，其值如下：</p>
<ul class="simple">
<li><a class="reference internal" href="#django.contrib.contenttypes.models.ContentType.app_label" title="django.contrib.contenttypes.models.ContentType.app_label"><code class="xref py py-attr docutils literal notranslate"><span class="pre">app_label</span></code></a> 将被设置为 <code class="docutils literal notranslate"><span class="pre">'sites'</span></code> （Python 路径 <code class="docutils literal notranslate"><span class="pre">django.contrib.sites</span></code> 的最后一部分）。</li>
<li><a class="reference internal" href="#django.contrib.contenttypes.models.ContentType.model" title="django.contrib.contenttypes.models.ContentType.model"><code class="xref py py-attr docutils literal notranslate"><span class="pre">model</span></code></a> 将被设置为 <code class="docutils literal notranslate"><span class="pre">'site'</span></code>。</li>
</ul>
</div>
<div class="section" id="s-methods-on-contenttype-instances">
<span id="methods-on-contenttype-instances"></span><h2><code class="docutils literal notranslate"><span class="pre">ContentType</span></code> 实例的方法<a class="headerlink" href="#methods-on-contenttype-instances" title="永久链接至标题">¶</a></h2>
<p>每个 <a class="reference internal" href="#django.contrib.contenttypes.models.ContentType" title="django.contrib.contenttypes.models.ContentType"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentType</span></code></a> 实例都有一些方法，允许你从 <a class="reference internal" href="#django.contrib.contenttypes.models.ContentType" title="django.contrib.contenttypes.models.ContentType"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentType</span></code></a> 实例获得它所代表的模型，或者从该模型中检索对象。</p>
<dl class="method">
<dt id="django.contrib.contenttypes.models.ContentType.get_object_for_this_type">
<code class="descclassname">ContentType.</code><code class="descname">get_object_for_this_type</code>(<em>**kwargs</em>)<a class="headerlink" href="#django.contrib.contenttypes.models.ContentType.get_object_for_this_type" title="永久链接至目标">¶</a></dt>
<dd><p>为 <a class="reference internal" href="#django.contrib.contenttypes.models.ContentType" title="django.contrib.contenttypes.models.ContentType"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentType</span></code></a> 所代表的模型获取一组有效的 <a class="reference internal" href="../../topics/db/queries.html#field-lookups-intro"><span class="std std-ref">查找参数</span></a>，并对该模型进行 <a class="reference internal" href="../models/querysets.html#django.db.models.query.QuerySet.get" title="django.db.models.query.QuerySet.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">一个</span> <span class="pre">get()</span> <span class="pre">查找</span></code></a>，返回相应的对象。</p>
</dd></dl>

<dl class="method">
<dt id="django.contrib.contenttypes.models.ContentType.model_class">
<code class="descclassname">ContentType.</code><code class="descname">model_class</code>()<a class="headerlink" href="#django.contrib.contenttypes.models.ContentType.model_class" title="永久链接至目标">¶</a></dt>
<dd><p>返回这个 <a class="reference internal" href="#django.contrib.contenttypes.models.ContentType" title="django.contrib.contenttypes.models.ContentType"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentType</span></code></a> 实例所代表的模型类。</p>
</dd></dl>

<p>例如，我们可以查找 <a class="reference internal" href="#django.contrib.contenttypes.models.ContentType" title="django.contrib.contenttypes.models.ContentType"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentType</span></code></a> 的 <a class="reference internal" href="auth.html#django.contrib.auth.models.User" title="django.contrib.auth.models.User"><code class="xref py py-class docutils literal notranslate"><span class="pre">User</span></code></a> 模型：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.contrib.contenttypes.models</span> <span class="kn">import</span> <span class="n">ContentType</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">user_type</span> <span class="o">=</span> <span class="n">ContentType</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">app_label</span><span class="o">=</span><span class="s1">&#39;auth&#39;</span><span class="p">,</span> <span class="n">model</span><span class="o">=</span><span class="s1">&#39;user&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">user_type</span>
<span class="go">&lt;ContentType: user&gt;</span>
</pre></div>
</div>
<p>然后用它来查询某个特定的 <a class="reference internal" href="auth.html#django.contrib.auth.models.User" title="django.contrib.auth.models.User"><code class="xref py py-class docutils literal notranslate"><span class="pre">User</span></code></a>，或者获取对 <code class="docutils literal notranslate"><span class="pre">User</span></code> 模型类的访问权：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">user_type</span><span class="o">.</span><span class="n">model_class</span><span class="p">()</span>
<span class="go">&lt;class &#39;django.contrib.auth.models.User&#39;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">user_type</span><span class="o">.</span><span class="n">get_object_for_this_type</span><span class="p">(</span><span class="n">username</span><span class="o">=</span><span class="s1">&#39;Guido&#39;</span><span class="p">)</span>
<span class="go">&lt;User: Guido&gt;</span>
</pre></div>
</div>
<p><a class="reference internal" href="#django.contrib.contenttypes.models.ContentType.get_object_for_this_type" title="django.contrib.contenttypes.models.ContentType.get_object_for_this_type"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_object_for_this_type()</span></code></a> 和 <code class="xref py py-meth docutils literal notranslate"><span class="pre">model_model_class()</span></code> 共同实现了两个极其重要的用例：</p>
<ol class="arabic simple">
<li>使用这些方法，你可以编写高级通用代码，在任何安装的模型上执行查询——而不是导入和使用一个特定的模型类，你可以在运行时将 <code class="docutils literal notranslate"><span class="pre">app_label</span></code> 和 <code class="docutils literal notranslate"><span class="pre">model</span></code> 传递到一个 <a class="reference internal" href="#django.contrib.contenttypes.models.ContentType" title="django.contrib.contenttypes.models.ContentType"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentType</span></code></a> 的查找中，然后与模型类一起工作，或者从中检索对象。</li>
<li>你可以将另一个模型与 <a class="reference internal" href="#django.contrib.contenttypes.models.ContentType" title="django.contrib.contenttypes.models.ContentType"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentType</span></code></a> 相关联，以此将它的实例与特定的模型类绑定，并使用这些方法来获取对这些模型类的访问。</li>
</ol>
<p>Django 的几个捆绑应用都使用了后一种技术。例如，Django 的认证框架中的 :class:<a href="#id1"><span class="problematic" id="id2">``</span></a>权限系统 &lt;django.contrib.auth.models.Permission&gt;` 使用了一个 <a class="reference internal" href="auth.html#django.contrib.auth.models.Permission" title="django.contrib.auth.models.Permission"><code class="xref py py-class docutils literal notranslate"><span class="pre">Permission</span></code></a> 模型，该模型的外键为 <a class="reference internal" href="#django.contrib.contenttypes.models.ContentType" title="django.contrib.contenttypes.models.ContentType"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentType</span></code></a>；这使得 <a class="reference internal" href="auth.html#django.contrib.auth.models.Permission" title="django.contrib.auth.models.Permission"><code class="xref py py-class docutils literal notranslate"><span class="pre">Permission</span></code></a> 可以表示“可以添加博客条目”或“可以删除新闻报道”等概念。</p>
<div class="section" id="s-the-contenttypemanager">
<span id="the-contenttypemanager"></span><h3><code class="docutils literal notranslate"><span class="pre">ContentTypeManager</span></code><a class="headerlink" href="#the-contenttypemanager" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.contrib.contenttypes.models.ContentTypeManager">
<em class="property">class </em><code class="descname">ContentTypeManager</code><a class="headerlink" href="#django.contrib.contenttypes.models.ContentTypeManager" title="永久链接至目标">¶</a></dt>
<dd><p><a class="reference internal" href="#django.contrib.contenttypes.models.ContentType" title="django.contrib.contenttypes.models.ContentType"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentType</span></code></a> 还有一个自定义管理器， <a class="reference internal" href="#django.contrib.contenttypes.models.ContentTypeManager" title="django.contrib.contenttypes.models.ContentTypeManager"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentTypeManager</span></code></a>，它增加了以下方法：</p>
<dl class="method">
<dt id="django.contrib.contenttypes.models.ContentTypeManager.clear_cache">
<code class="descname">clear_cache</code>()<a class="headerlink" href="#django.contrib.contenttypes.models.ContentTypeManager.clear_cache" title="永久链接至目标">¶</a></dt>
<dd><p>清除 <a class="reference internal" href="#django.contrib.contenttypes.models.ContentType" title="django.contrib.contenttypes.models.ContentType"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentType</span></code></a> 内部的缓存，用来跟踪已经创建了 <a class="reference internal" href="#django.contrib.contenttypes.models.ContentType" title="django.contrib.contenttypes.models.ContentType"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentType</span></code></a> 实例的模型。你可能永远都不需要自己调用这个方法，Django 会在需要的时候自动调用它。</p>
</dd></dl>

<dl class="method">
<dt id="django.contrib.contenttypes.models.ContentTypeManager.get_for_id">
<code class="descname">get_for_id</code>(<em>id</em>)<a class="headerlink" href="#django.contrib.contenttypes.models.ContentTypeManager.get_for_id" title="永久链接至目标">¶</a></dt>
<dd><p>通过 ID 查找一个 <a class="reference internal" href="#django.contrib.contenttypes.models.ContentType" title="django.contrib.contenttypes.models.ContentType"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentType</span></code></a>。由于该方法与 <a class="reference internal" href="#django.contrib.contenttypes.models.ContentTypeManager.get_for_model" title="django.contrib.contenttypes.models.ContentTypeManager.get_for_model"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_for_model()</span></code></a> 使用了相同的共享缓存，所以最好使用该方法，而不是通常的 <code class="docutils literal notranslate"><span class="pre">ContentType.objects.get(pk=id)</span></code>。</p>
</dd></dl>

<dl class="method">
<dt id="django.contrib.contenttypes.models.ContentTypeManager.get_for_model">
<code class="descname">get_for_model</code>(<em>model</em>, <em>for_concrete_model=True</em>)<a class="headerlink" href="#django.contrib.contenttypes.models.ContentTypeManager.get_for_model" title="永久链接至目标">¶</a></dt>
<dd><p>取一个模型类或一个模型的实例，并返回代表该模型的 <a class="reference internal" href="#django.contrib.contenttypes.models.ContentType" title="django.contrib.contenttypes.models.ContentType"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentType</span></code></a> 实例。<code class="docutils literal notranslate"><span class="pre">for_concrete_model=False</span></code> 允许获取代理模型的 <a class="reference internal" href="#django.contrib.contenttypes.models.ContentType" title="django.contrib.contenttypes.models.ContentType"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentType</span></code></a> 实例。</p>
</dd></dl>

<dl class="method">
<dt id="django.contrib.contenttypes.models.ContentTypeManager.get_for_models">
<code class="descname">get_for_models</code>(<em>*models</em>, <em>for_concrete_models=True</em>)<a class="headerlink" href="#django.contrib.contenttypes.models.ContentTypeManager.get_for_models" title="永久链接至目标">¶</a></dt>
<dd><p>取一个数量不等的模型类，并返回一个将模型类映射到代表它们的 <a class="reference internal" href="#django.contrib.contenttypes.models.ContentType" title="django.contrib.contenttypes.models.ContentType"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentType</span></code></a> 实例的字典。<code class="docutils literal notranslate"><span class="pre">for_concrete_models=False</span></code> 允许获取代理模型的 <a class="reference internal" href="#django.contrib.contenttypes.models.ContentType" title="django.contrib.contenttypes.models.ContentType"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentType</span></code></a> 实例。</p>
</dd></dl>

<dl class="method">
<dt id="django.contrib.contenttypes.models.ContentTypeManager.get_by_natural_key">
<code class="descname">get_by_natural_key</code>(<em>app_label</em>, <em>model</em>)<a class="headerlink" href="#django.contrib.contenttypes.models.ContentTypeManager.get_by_natural_key" title="永久链接至目标">¶</a></dt>
<dd><p>返回由给定的应用程序标签和模型名称唯一标识的 <a class="reference internal" href="#django.contrib.contenttypes.models.ContentType" title="django.contrib.contenttypes.models.ContentType"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentType</span></code></a> 实例。本方法的主要目的是允许 <a class="reference internal" href="#django.contrib.contenttypes.models.ContentType" title="django.contrib.contenttypes.models.ContentType"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentType</span></code></a> 对象在反序列化过程中通过 <a class="reference internal" href="../../topics/serialization.html#topics-serialization-natural-keys"><span class="std std-ref">自然键</span></a> 被引用。</p>
</dd></dl>

</dd></dl>

<p>当你知道需要使用一个 <a class="reference internal" href="#django.contrib.contenttypes.models.ContentType" title="django.contrib.contenttypes.models.ContentType"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentType</span></code></a>，但又不想麻烦地获取模型的元数据来执行手动查找时，这个 <a class="reference internal" href="#django.contrib.contenttypes.models.ContentTypeManager.get_for_model" title="django.contrib.contenttypes.models.ContentTypeManager.get_for_model"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_for_model()</span></code></a> 方法特别有用：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.contrib.auth.models</span> <span class="kn">import</span> <span class="n">User</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ContentType</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get_for_model</span><span class="p">(</span><span class="n">User</span><span class="p">)</span>
<span class="go">&lt;ContentType: user&gt;</span>
</pre></div>
</div>
<span class="target" id="module-django.contrib.contenttypes.fields"></span></div>
</div>
<div class="section" id="s-generic-relations">
<span id="s-id1"></span><span id="generic-relations"></span><span id="id1"></span><h2>通用关系<a class="headerlink" href="#generic-relations" title="永久链接至标题">¶</a></h2>
<p>在 <a class="reference internal" href="#django.contrib.contenttypes.models.ContentType" title="django.contrib.contenttypes.models.ContentType"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentType</span></code></a> 中添加一个来自你自己模型的外键，可以让你的模型有效地将自己与另一个模型类绑定，就像上面 <code class="xref py py-class docutils literal notranslate"><span class="pre">Permission</span></code> 模型的例子一样。但也可以更进一步，使用 <code class="xref py py-class docutils literal notranslate"><span class="pre">ContentType</span></code> 来实现模型之间真正的通用（有时也称为 “多态”）关系。</p>
<p>例如，它可以用于这样的标签系统：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.contrib.contenttypes.fields</span> <span class="kn">import</span> <span class="n">GenericForeignKey</span>
<span class="kn">from</span> <span class="nn">django.contrib.contenttypes.models</span> <span class="kn">import</span> <span class="n">ContentType</span>
<span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">TaggedItem</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">tag</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">SlugField</span><span class="p">()</span>
    <span class="n">content_type</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">ContentType</span><span class="p">,</span> <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">)</span>
    <span class="n">object_id</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">PositiveIntegerField</span><span class="p">()</span>
    <span class="n">content_object</span> <span class="o">=</span> <span class="n">GenericForeignKey</span><span class="p">(</span><span class="s1">&#39;content_type&#39;</span><span class="p">,</span> <span class="s1">&#39;object_id&#39;</span><span class="p">)</span>

    <span class="k">def</span> <span class="fm">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">tag</span>
</pre></div>
</div>
<p>一个普通的 <a class="reference internal" href="../models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a> 只能 “指向” 一个其他模型，这意味着如果 <code class="docutils literal notranslate"><span class="pre">TaggedItem</span></code> 模型使用 <a class="reference internal" href="../models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a>，它将不得不选择一个且仅有一个模型来存储标签。contenttypes 应用程序提供了一个特殊的字段类型 （<code class="docutils literal notranslate"><span class="pre">GenericForeignKey</span></code>），它可以解决这个问题，并允许与任何模型建立关系：</p>
<dl class="class">
<dt id="django.contrib.contenttypes.fields.GenericForeignKey">
<em class="property">class </em><code class="descname">GenericForeignKey</code><a class="headerlink" href="#django.contrib.contenttypes.fields.GenericForeignKey" title="永久链接至目标">¶</a></dt>
<dd><p>设置一个 <a class="reference internal" href="#django.contrib.contenttypes.fields.GenericForeignKey" title="django.contrib.contenttypes.fields.GenericForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">GenericForeignKey</span></code></a> 分为三步：</p>
<ol class="arabic simple">
<li>给你的模型一个 <a class="reference internal" href="../models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a> 到 <a class="reference internal" href="#django.contrib.contenttypes.models.ContentType" title="django.contrib.contenttypes.models.ContentType"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentType</span></code></a>。这个字段的通常名称是 “content_type”。</li>
<li>给你的模型一个字段，它可以存储你要关联的模型的主键值。对于大多数模型来说，这意味着一个 <a class="reference internal" href="../models/fields.html#django.db.models.PositiveIntegerField" title="django.db.models.PositiveIntegerField"><code class="xref py py-class docutils literal notranslate"><span class="pre">PositiveIntegerField</span></code></a>。这个字段的通常名称是 “object_id”。</li>
<li>给你的模型一个 <a class="reference internal" href="#django.contrib.contenttypes.fields.GenericForeignKey" title="django.contrib.contenttypes.fields.GenericForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">GenericForeignKey</span></code></a>，并把上面描述的两个字段的名字传给它。如果这些字段的名字是 “content_type” 和 “object_id”，你可以省略这一点 —— 这些是 <code class="xref py py-class docutils literal notranslate"><span class="pre">GenericForeignKey</span></code> 会查找的默认字段名。</li>
</ol>
<dl class="attribute">
<dt id="django.contrib.contenttypes.fields.GenericForeignKey.for_concrete_model">
<code class="descname">for_concrete_model</code><a class="headerlink" href="#django.contrib.contenttypes.fields.GenericForeignKey.for_concrete_model" title="永久链接至目标">¶</a></dt>
<dd><p>如果 <code class="docutils literal notranslate"><span class="pre">False</span></code>，该字段将能够引用代理模型。默认值是 <code class="docutils literal notranslate"><span class="pre">True</span></code>。这与 <a class="reference internal" href="#django.contrib.contenttypes.models.ContentTypeManager.get_for_model" title="django.contrib.contenttypes.models.ContentTypeManager.get_for_model"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_for_model()</span></code></a> 的 <code class="docutils literal notranslate"><span class="pre">for_concrete_model</span></code> 参数一致。</p>
</dd></dl>

</dd></dl>

<div class="admonition-primary-key-type-compatibility admonition">
<p class="first admonition-title">主键类型兼容性</p>
<p>“object_id” 字段不一定要和相关模型上的主键字段是同一类型，但它们的主键值必须通过其 <a class="reference internal" href="../models/fields.html#django.db.models.Field.get_db_prep_value" title="django.db.models.Field.get_db_prep_value"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_db_prep_value()</span></code></a> 方法与 “object_id” 字段的类型一致。</p>
<p>例如，如果你想允许通用关系到具有 <code class="xref py py-class docutils literal notranslate"><span class="pre">CharField</span></code> 主键字段的模型，你可以使用 <a class="reference internal" href="../models/fields.html#django.db.models.CharField" title="django.db.models.CharField"><code class="xref py py-class docutils literal notranslate"><span class="pre">CharField</span></code></a> 作为你的模型上的 “object_id” 字段，因为整数可以通过 <a class="reference internal" href="../models/fields.html#django.db.models.Field.get_db_prep_value" title="django.db.models.Field.get_db_prep_value"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_db_prep_value()</span></code></a> 强制转换成字符串。</p>
<p>为了获得最大的灵活性，你可以使用一个 <a class="reference internal" href="../models/fields.html#django.db.models.TextField" title="django.db.models.TextField"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextField</span></code></a>，它没有定义最大的长度，但是这可能会根据你的数据库后端产生显著的性能惩罚。</p>
<p class="last">对于哪种字段类型最好，没有一个放之四海而皆准的解决方案。你应该评估你期望指向的模型，并确定哪种解决方案对你的用例最有效。</p>
</div>
<div class="admonition-serializing-references-to-contenttype-objects admonition">
<p class="first admonition-title">序列化对 <code class="docutils literal notranslate"><span class="pre">ContentType</span></code> 对象的引用</p>
<p class="last">如果你正在从实现通用关系的模型中序列化数据（例如，在生成 <a class="reference internal" href="../../topics/testing/tools.html#django.test.TransactionTestCase.fixtures" title="django.test.TransactionTestCase.fixtures"><code class="xref py py-class docutils literal notranslate"><span class="pre">fixtures</span></code></a> 时），你可能应该使用自然键来唯一地识别相关的 <a class="reference internal" href="#django.contrib.contenttypes.models.ContentType" title="django.contrib.contenttypes.models.ContentType"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentType</span></code></a> 对象。参见 <a class="reference internal" href="../../topics/serialization.html#topics-serialization-natural-keys"><span class="std std-ref">自然键</span></a> 和 <a class="reference internal" href="../django-admin.html#cmdoption-dumpdata-natural-foreign"><code class="xref std std-option docutils literal notranslate"><span class="pre">dumpdata</span> <span class="pre">--natural-foreign</span></code></a> 了解更多信息。</p>
</div>
<p>这将启用一个类似于普通 <a class="reference internal" href="../models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a> 的 API；每个 <code class="docutils literal notranslate"><span class="pre">TaggedItem</span></code> 都会有一个 <code class="docutils literal notranslate"><span class="pre">content_object</span></code> 字段，返回与之相关的对象，你也可以在创建 <code class="docutils literal notranslate"><span class="pre">TaggedItem</span></code> 时将其赋值给该字段或使用：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">django.contrib.auth.models</span> <span class="kn">import</span> <span class="n">User</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">guido</span> <span class="o">=</span> <span class="n">User</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">username</span><span class="o">=</span><span class="s1">&#39;Guido&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="n">TaggedItem</span><span class="p">(</span><span class="n">content_object</span><span class="o">=</span><span class="n">guido</span><span class="p">,</span> <span class="n">tag</span><span class="o">=</span><span class="s1">&#39;bdfl&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="o">.</span><span class="n">content_object</span>
<span class="go">&lt;User: Guido&gt;</span>
</pre></div>
</div>
<p>如果相关对象被删除，<code class="docutils literal notranslate"><span class="pre">content_type</span></code> 和 <code class="docutils literal notranslate"><span class="pre">object_id</span></code> 字段保持原值，<code class="docutils literal notranslate"><span class="pre">GenericForeignKey</span></code> 返回 <code class="docutils literal notranslate"><span class="pre">None</span></code>：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">guido</span><span class="o">.</span><span class="n">delete</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="o">.</span><span class="n">content_object</span>  <span class="c1"># returns None</span>
</pre></div>
</div>
<p>由于 <a class="reference internal" href="#django.contrib.contenttypes.fields.GenericForeignKey" title="django.contrib.contenttypes.fields.GenericForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">GenericForeignKey</span></code></a> 的实现方式，你不能通过数据库 API 直接使用这种字段与过滤器（例如 <code class="docutils literal notranslate"><span class="pre">filter()</span></code> 和 <code class="docutils literal notranslate"><span class="pre">exclude()</span></code>）。因为一个 <a class="reference internal" href="#django.contrib.contenttypes.fields.GenericForeignKey" title="django.contrib.contenttypes.fields.GenericForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">GenericForeignKey</span></code></a> 不是一个普通的字段对象，所以这些例子将 <em>无法</em> 工作：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># This will fail</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">TaggedItem</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">content_object</span><span class="o">=</span><span class="n">guido</span><span class="p">)</span>
<span class="c1"># This will also fail</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">TaggedItem</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">content_object</span><span class="o">=</span><span class="n">guido</span><span class="p">)</span>
</pre></div>
</div>
<p>同样， <a class="reference internal" href="#django.contrib.contenttypes.fields.GenericForeignKey" title="django.contrib.contenttypes.fields.GenericForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">GenericForeignKey</span></code></a> 也没有出现在 <a class="reference internal" href="../../topics/forms/modelforms.html#django.forms.ModelForm" title="django.forms.ModelForm"><code class="xref py py-class docutils literal notranslate"><span class="pre">ModelForm</span></code></a> 中。</p>
<div class="section" id="s-reverse-generic-relations">
<span id="reverse-generic-relations"></span><h3>反查通用关系<a class="headerlink" href="#reverse-generic-relations" title="永久链接至标题">¶</a></h3>
<dl class="class">
<dt id="django.contrib.contenttypes.fields.GenericRelation">
<em class="property">class </em><code class="descname">GenericRelation</code><a class="headerlink" href="#django.contrib.contenttypes.fields.GenericRelation" title="永久链接至目标">¶</a></dt>
<dd><dl class="attribute">
<dt id="django.contrib.contenttypes.fields.GenericRelation.related_query_name">
<code class="descname">related_query_name</code><a class="headerlink" href="#django.contrib.contenttypes.fields.GenericRelation.related_query_name" title="永久链接至目标">¶</a></dt>
<dd><p>默认情况下，相关对象与本对象的关系并不存在。设置 <code class="docutils literal notranslate"><span class="pre">related_query_name</span></code> 创建一个从相关对象到这个对象的关系。这样就可以从关联对象中进行查询和过滤。</p>
</dd></dl>

</dd></dl>

<p>如果你知道哪些模型你会最经常使用，你也可以添加一个 “反向” 的通用关系来启用一个额外的 API。例如：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.contrib.contenttypes.fields</span> <span class="kn">import</span> <span class="n">GenericRelation</span>
<span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Bookmark</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">url</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">URLField</span><span class="p">()</span>
    <span class="n">tags</span> <span class="o">=</span> <span class="n">GenericRelation</span><span class="p">(</span><span class="n">TaggedItem</span><span class="p">)</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">Bookmark</span></code> 实例将有一个 <code class="docutils literal notranslate"><span class="pre">tags</span></code> 属性，可用于检索其相关的 <code class="docutils literal notranslate"><span class="pre">TaggedItems</span></code>：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="n">Bookmark</span><span class="p">(</span><span class="n">url</span><span class="o">=</span><span class="s1">&#39;https://www.djangoproject.com/&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t1</span> <span class="o">=</span> <span class="n">TaggedItem</span><span class="p">(</span><span class="n">content_object</span><span class="o">=</span><span class="n">b</span><span class="p">,</span> <span class="n">tag</span><span class="o">=</span><span class="s1">&#39;django&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t1</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t2</span> <span class="o">=</span> <span class="n">TaggedItem</span><span class="p">(</span><span class="n">content_object</span><span class="o">=</span><span class="n">b</span><span class="p">,</span> <span class="n">tag</span><span class="o">=</span><span class="s1">&#39;python&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t2</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">tags</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">&lt;QuerySet [&lt;TaggedItem: django&gt;, &lt;TaggedItem: python&gt;]&gt;</span>
</pre></div>
</div>
<p>你也可以使用 <code class="docutils literal notranslate"><span class="pre">add()</span></code>、<code class="docutils literal notranslate"><span class="pre">create()</span></code> 或 <code class="docutils literal notranslate"><span class="pre">set()</span></code> 来创建关系：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">t3</span> <span class="o">=</span> <span class="n">TaggedItem</span><span class="p">(</span><span class="n">tag</span><span class="o">=</span><span class="s1">&#39;Web development&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">tags</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">t3</span><span class="p">,</span> <span class="n">bulk</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">tags</span><span class="o">.</span><span class="n">create</span><span class="p">(</span><span class="n">tag</span><span class="o">=</span><span class="s1">&#39;Web framework&#39;</span><span class="p">)</span>
<span class="go">&lt;TaggedItem: Web framework&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">tags</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">&lt;QuerySet [&lt;TaggedItem: django&gt;, &lt;TaggedItem: python&gt;, &lt;TaggedItem: Web development&gt;, &lt;TaggedItem: Web framework&gt;]&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">tags</span><span class="o">.</span><span class="n">set</span><span class="p">([</span><span class="n">t1</span><span class="p">,</span> <span class="n">t3</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">tags</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">&lt;QuerySet [&lt;TaggedItem: django&gt;, &lt;TaggedItem: Web development&gt;]&gt;</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">remove()</span></code> 调用将批量删除指定的模型对象：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">tags</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="n">t3</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">tags</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">&lt;QuerySet [&lt;TaggedItem: django&gt;]&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">TaggedItem</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">&lt;QuerySet [&lt;TaggedItem: django&gt;]&gt;</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">clear()</span></code> 方法可以用来批量删除一个实例的所有相关对象：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">tags</span><span class="o">.</span><span class="n">clear</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">tags</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">&lt;QuerySet []&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">TaggedItem</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
<span class="go">&lt;QuerySet []&gt;</span>
</pre></div>
</div>
<p>定义 <a class="reference internal" href="#django.contrib.contenttypes.fields.GenericRelation" title="django.contrib.contenttypes.fields.GenericRelation"><code class="xref py py-class docutils literal notranslate"><span class="pre">GenericRelation</span></code></a>，并设置 <code class="docutils literal notranslate"><span class="pre">related_query_name</span></code> 允许从相关对象查询：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">tags</span> <span class="o">=</span> <span class="n">GenericRelation</span><span class="p">(</span><span class="n">TaggedItem</span><span class="p">,</span> <span class="n">related_query_name</span><span class="o">=</span><span class="s1">&#39;bookmark&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>这样就可以从 <code class="docutils literal notranslate"><span class="pre">TaggedItem</span></code> 对 <code class="docutils literal notranslate"><span class="pre">Bookmark</span></code> 进行过滤、排序和其他查询操作：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># Get all tags belonging to bookmarks containing `django` in the url</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">TaggedItem</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">bookmark__url__contains</span><span class="o">=</span><span class="s1">&#39;django&#39;</span><span class="p">)</span>
<span class="go">&lt;QuerySet [&lt;TaggedItem: django&gt;, &lt;TaggedItem: python&gt;]&gt;</span>
</pre></div>
</div>
<p>如果你不添加 <code class="docutils literal notranslate"><span class="pre">related_query_name</span></code>，你可以手动进行相同类型的查询：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">bookmarks</span> <span class="o">=</span> <span class="n">Bookmark</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">url__contains</span><span class="o">=</span><span class="s1">&#39;django&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">bookmark_type</span> <span class="o">=</span> <span class="n">ContentType</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get_for_model</span><span class="p">(</span><span class="n">Bookmark</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">TaggedItem</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">content_type__pk</span><span class="o">=</span><span class="n">bookmark_type</span><span class="o">.</span><span class="n">id</span><span class="p">,</span> <span class="n">object_id__in</span><span class="o">=</span><span class="n">bookmarks</span><span class="p">)</span>
<span class="go">&lt;QuerySet [&lt;TaggedItem: django&gt;, &lt;TaggedItem: python&gt;]&gt;</span>
</pre></div>
</div>
<p>正如 <code class="xref py py-class docutils literal notranslate"><span class="pre">GenericForeignKey</span></code> 接受content-type 和 object-ID 字段的名称作为参数一样， <code class="xref py py-class docutils literal notranslate"><span class="pre">GenericRelation</span></code> 也是如此；如果拥有通用外键的模型对这些字段使用了非默认的名称，那么在给它设置 <a class="reference internal" href="#django.contrib.contenttypes.fields.GenericRelation" title="django.contrib.contenttypes.fields.GenericRelation"><code class="xref py py-class docutils literal notranslate"><span class="pre">GenericRelation</span></code></a> 时必须传递这些字段的名称。例如，如果上面提到的 <code class="docutils literal notranslate"><span class="pre">TaggedItem</span></code> 模型使用了名为 <code class="docutils literal notranslate"><span class="pre">content_type_fk</span></code> 和 <code class="docutils literal notranslate"><span class="pre">object_primary_key</span></code> 的字段来创建它的通用外键，那么回传给它的 <a class="reference internal" href="#django.contrib.contenttypes.fields.GenericRelation" title="django.contrib.contenttypes.fields.GenericRelation"><code class="xref py py-class docutils literal notranslate"><span class="pre">GenericRelation</span></code></a> 就需要这样定义：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">tags</span> <span class="o">=</span> <span class="n">GenericRelation</span><span class="p">(</span>
    <span class="n">TaggedItem</span><span class="p">,</span>
    <span class="n">content_type_field</span><span class="o">=</span><span class="s1">&#39;content_type_fk&#39;</span><span class="p">,</span>
    <span class="n">object_id_field</span><span class="o">=</span><span class="s1">&#39;object_primary_key&#39;</span><span class="p">,</span>
<span class="p">)</span>
</pre></div>
</div>
<p>还要注意的是，如果你删除了一个有 <code class="xref py py-class docutils literal notranslate"><span class="pre">GenericRelation</span></code> 的对象，任何有 <code class="xref py py-class docutils literal notranslate"><span class="pre">GenericForeignKey</span></code> 指向它的对象也会被删除。在上面的例子中，这意味着如果一个 <code class="docutils literal notranslate"><span class="pre">Bookmark</span></code> 对象被删除，任何指向它的 <code class="docutils literal notranslate"><span class="pre">TaggedItem</span></code> 对象也会同时被删除。</p>
<p>与 <a class="reference internal" href="../models/fields.html#django.db.models.ForeignKey" title="django.db.models.ForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForeignKey</span></code></a> 不同， <code class="xref py py-class docutils literal notranslate"><span class="pre">GenericForeignKey</span></code> 不接受 <code class="xref py py-attr docutils literal notranslate"> <span class="pre">on_delete</span></code> 参数来定制这个行为；如果需要，可以不使用 <code class="xref py py-class docutils literal notranslate"><span class="pre">GenericRelation</span></code> 来避免级联删除，可以通过 <a class="reference internal" href="../signals.html#django.db.models.signals.pre_delete" title="django.db.models.signals.pre_delete"><code class="xref py py-data docutils literal notranslate"><span class="pre">pre_delete</span></code></a> 信号来提供替代行为。</p>
</div>
<div class="section" id="s-generic-relations-and-aggregation">
<span id="generic-relations-and-aggregation"></span><h3>通用关系和聚合<a class="headerlink" href="#generic-relations-and-aggregation" title="永久链接至标题">¶</a></h3>
<p><a class="reference internal" href="../../topics/db/aggregation.html"><span class="doc">Django 的数据库聚合 API</span></a> 的工作原理是 <code class="xref py py-class docutils literal notranslate"><span class="pre">GenericRelation</span></code>。例如，你可以找出所有书签有多少个标签：</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Bookmark</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">aggregate</span><span class="p">(</span><span class="n">Count</span><span class="p">(</span><span class="s1">&#39;tags&#39;</span><span class="p">))</span>
<span class="go">{&#39;tags__count&#39;: 3}</span>
</pre></div>
</div>
<span class="target" id="module-django.contrib.contenttypes.forms"></span></div>
<div class="section" id="s-generic-relation-in-forms">
<span id="generic-relation-in-forms"></span><h3>表单中的通用关系<a class="headerlink" href="#generic-relation-in-forms" title="永久链接至标题">¶</a></h3>
<p><a class="reference internal" href="#module-django.contrib.contenttypes.forms" title="django.contrib.contenttypes.forms"><code class="xref py py-mod docutils literal notranslate"><span class="pre">django.contrib.contenttypes.forms</span></code></a> 模块提供：</p>
<ul class="simple">
<li><a class="reference internal" href="#django.contrib.contenttypes.forms.BaseGenericInlineFormSet" title="django.contrib.contenttypes.forms.BaseGenericInlineFormSet"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseGenericInlineFormSet</span></code></a></li>
<li>一个表单集工厂， <a class="reference internal" href="#django.contrib.contenttypes.forms.generic_inlineformset_factory" title="django.contrib.contenttypes.forms.generic_inlineformset_factory"><code class="xref py py-func docutils literal notranslate"><span class="pre">generic_inlineformset_factory()</span></code></a>，用于 <a class="reference internal" href="#django.contrib.contenttypes.fields.GenericForeignKey" title="django.contrib.contenttypes.fields.GenericForeignKey"><code class="xref py py-class docutils literal notranslate"><span class="pre">GenericForeignKey</span></code></a>。</li>
</ul>
<dl class="class">
<dt id="django.contrib.contenttypes.forms.BaseGenericInlineFormSet">
<em class="property">class </em><code class="descname">BaseGenericInlineFormSet</code><a class="headerlink" href="#django.contrib.contenttypes.forms.BaseGenericInlineFormSet" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<dl class="function">
<dt id="django.contrib.contenttypes.forms.generic_inlineformset_factory">
<code class="descname">generic_inlineformset_factory</code>(<em>model</em>, <em>form=ModelForm</em>, <em>formset=BaseGenericInlineFormSet</em>, <em>ct_field=&quot;content_type&quot;</em>, <em>fk_field=&quot;object_id&quot;</em>, <em>fields=None</em>, <em>exclude=None</em>, <em>extra=3</em>, <em>can_order=False</em>, <em>can_delete=True</em>, <em>max_num=None</em>, <em>formfield_callback=None</em>, <em>validate_max=False</em>, <em>for_concrete_model=True</em>, <em>min_num=None</em>, <em>validate_min=False</em>, <em>absolute_max=None</em>, <em>can_delete_extra=True</em>)<a class="headerlink" href="#django.contrib.contenttypes.forms.generic_inlineformset_factory" title="永久链接至目标">¶</a></dt>
<dd><p>使用 <code class="xref py py-func docutils literal notranslate"><span class="pre">modelormset_factory()</span></code> 返回一个 <code class="docutils literal notranslate"><span class="pre">GenericInlineFormSet</span></code>。</p>
<p>你必须提供 <code class="docutils literal notranslate"><span class="pre">ct_field</span></code> 和 <code class="docutils literal notranslate"><span class="pre">fk_field</span></code>，如果它们与默认值 <code class="docutils literal notranslate"><span class="pre">content_type</span></code> 和 <code class="docutils literal notranslate"><span class="pre">object_id</span></code> 不同。其他参数与 <code class="xref py py-func docutils literal notranslate"><span class="pre">modelselformset_factory()</span></code> 和 <a class="reference internal" href="../forms/models.html#django.forms.models.inlineformset_factory" title="django.forms.models.inlineformset_factory"><code class="xref py py-func docutils literal notranslate"><span class="pre">inlineformset_factory()</span></code></a> 中记载的类似。</p>
<p><code class="docutils literal notranslate"><span class="pre">for_concrete_model</span></code> 参数对应于 <code class="xref py py-class docutils literal notranslate"><span class="pre">for_concrete_model`</span></code> 参数。</p>
<div class="versionchanged">
<span class="title">Changed in Django 3.2:</span> <p>增加了 <code class="docutils literal notranslate"><span class="pre">absolute_max</span></code> 和 <code class="docutils literal notranslate"><span class="pre">can_delete_extra</span></code> 参数。</p>
</div>
</dd></dl>

<span class="target" id="module-django.contrib.contenttypes.admin"></span></div>
<div class="section" id="s-generic-relations-in-admin">
<span id="generic-relations-in-admin"></span><h3>管理中的通用关系<a class="headerlink" href="#generic-relations-in-admin" title="永久链接至标题">¶</a></h3>
<p><a class="reference internal" href="#module-django.contrib.contenttypes.admin" title="django.contrib.contenttypes.admin"><code class="xref py py-mod docutils literal notranslate"><span class="pre">django.contrib.contenttypes.admin</span></code></a> 模块提供了 <a class="reference internal" href="#django.contrib.contenttypes.admin.GenericTabularInline" title="django.contrib.contenttypes.admin.GenericTabularInline"><code class="xref py py-class docutils literal notranslate"><span class="pre">GenericTabularInline</span></code></a> 和 <code class="xref py py-class docutils literal notranslate"><span class="pre">GenericInlineModelAdmin</span></code> 的子类）。</p>
<p>这些类和函数可以在表单和管理中使用通用关系。更多信息请参见 <a class="reference internal" href="../../topics/forms/modelforms.html"><span class="doc">模型表单集</span></a> 和 <a class="reference internal" href="admin/index.html#using-generic-relations-as-an-inline"><span class="std std-ref">管理</span></a> 文档。</p>
<dl class="class">
<dt id="django.contrib.contenttypes.admin.GenericInlineModelAdmin">
<em class="property">class </em><code class="descname">GenericInlineModelAdmin</code><a class="headerlink" href="#django.contrib.contenttypes.admin.GenericInlineModelAdmin" title="永久链接至目标">¶</a></dt>
<dd><p><a class="reference internal" href="#django.contrib.contenttypes.admin.GenericInlineModelAdmin" title="django.contrib.contenttypes.admin.GenericInlineModelAdmin"><code class="xref py py-class docutils literal notranslate"><span class="pre">GenericInlineModelAdmin</span></code></a> 类继承了 <a class="reference internal" href="admin/index.html#django.contrib.admin.InlineModelAdmin" title="django.contrib.admin.InlineModelAdmin"><code class="xref py py-class docutils literal notranslate"><span class="pre">InlineModelAdmin</span></code></a> 类的所有属性。然而，它增加了一些自己的属性来处理通用关系：</p>
<dl class="attribute">
<dt id="django.contrib.contenttypes.admin.GenericInlineModelAdmin.ct_field">
<code class="descname">ct_field</code><a class="headerlink" href="#django.contrib.contenttypes.admin.GenericInlineModelAdmin.ct_field" title="永久链接至目标">¶</a></dt>
<dd><p>模型上的 <a class="reference internal" href="#django.contrib.contenttypes.models.ContentType" title="django.contrib.contenttypes.models.ContentType"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentType</span></code></a> 外键字段的名称。默认为 <code class="docutils literal notranslate"><span class="pre">content_type</span></code>。</p>
</dd></dl>

<dl class="attribute">
<dt id="django.contrib.contenttypes.admin.GenericInlineModelAdmin.ct_fk_field">
<code class="descname">ct_fk_field</code><a class="headerlink" href="#django.contrib.contenttypes.admin.GenericInlineModelAdmin.ct_fk_field" title="永久链接至目标">¶</a></dt>
<dd><p>代表相关对象 ID 的整数字段的名称。默认值为 <code class="docutils literal notranslate"><span class="pre">object_id</span></code>。</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="django.contrib.contenttypes.admin.GenericTabularInline">
<em class="property">class </em><code class="descname">GenericTabularInline</code><a class="headerlink" href="#django.contrib.contenttypes.admin.GenericTabularInline" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<dl class="class">
<dt id="django.contrib.contenttypes.admin.GenericStackedInline">
<em class="property">class </em><code class="descname">GenericStackedInline</code><a class="headerlink" href="#django.contrib.contenttypes.admin.GenericStackedInline" title="永久链接至目标">¶</a></dt>
<dd><p><a class="reference internal" href="#django.contrib.contenttypes.admin.GenericInlineModelAdmin" title="django.contrib.contenttypes.admin.GenericInlineModelAdmin"><code class="xref py py-class docutils literal notranslate"><span class="pre">GenericInlineModelAdmin</span></code></a> 的子类，分别具有堆栈式和表格式布局。</p>
</dd></dl>

</div>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">内容类型框架</a><ul>
<li><a class="reference internal" href="#overview">概况</a></li>
<li><a class="reference internal" href="#installing-the-contenttypes-framework">安装内容类型框架</a></li>
<li><a class="reference internal" href="#the-contenttype-model"><code class="docutils literal notranslate"><span class="pre">ContentType</span></code> 模型</a></li>
<li><a class="reference internal" href="#methods-on-contenttype-instances"><code class="docutils literal notranslate"><span class="pre">ContentType</span></code> 实例的方法</a><ul>
<li><a class="reference internal" href="#the-contenttypemanager"><code class="docutils literal notranslate"><span class="pre">ContentTypeManager</span></code></a></li>
</ul>
</li>
<li><a class="reference internal" href="#generic-relations">通用关系</a><ul>
<li><a class="reference internal" href="#reverse-generic-relations">反查通用关系</a></li>
<li><a class="reference internal" href="#generic-relations-and-aggregation">通用关系和聚合</a></li>
<li><a class="reference internal" href="#generic-relation-in-forms">表单中的通用关系</a></li>
<li><a class="reference internal" href="#generic-relations-in-admin">管理中的通用关系</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="auth.html"
                        title="上一章"><code class="docutils literal notranslate"><span class="pre">django.contrib.auth</span></code></a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="flatpages.html"
                        title="下一章">简单页面应用</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../../_sources/ref/contrib/contenttypes.txt"
            rel="nofollow">显示源代码</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>快速搜索</h3>
    <div class="searchformwrapper">
    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="转向" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">7月 23, 2021</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="auth.html" title="&lt;code class=&#34;docutils literal notranslate&#34;&gt;&lt;span class=&#34;pre&#34;&gt;django.contrib.auth&lt;/span&gt;&lt;/code&gt;">previous</a>
     |
    <a href="../index.html" title="API 参考" accesskey="U">up</a>
   |
    <a href="flatpages.html" title="简单页面应用">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>